import { Component, forwardRef, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, Validator } from '@angular/forms';

@Component({
  selector: 'app-number-input',
  templateUrl: './number-input.component.html',
  styleUrls: ['./number-input.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => NumberInputComponent),
      multi: true
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => NumberInputComponent),
      multi: true
    }
  ]
})
export class NumberInputComponent {
  @Input() max: number;
  @Input() min: number;
  @Input() placeholder: string = '';
  @Input() allowEmpty: boolean = false;
  @Input() decimalLimit: number | null = null;
  @Input() pattern: RegExp | null = null;
  @Input() isDisabled: boolean = false;
  @Input() isReadonly: boolean = false;

  value: number | '' = '';
  onChange = (value: any) => {};
  onTouched = () => {};

  writeValue(value: any): void {
    this.value = value;
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  onModelChange(value: any): void {
    if (this.allowEmpty && value === '') {
      this.value = '';
      this.onChange(this.value);
      return;
    }
    let num = parseFloat(value);
    if (!isNaN(num) && this.checkValueInRange(num)) {
      this.value = num;
      this.onChange(this.value);
    }
  }

  onInput(event: any): void {
    let value = event.target.value;
    if (this.decimalLimit != null && this.pattern == null) {
      const regex = new RegExp(`^-?\\d*(\\.\\d{0,${this.decimalLimit}})?`);
      const match = value.match(regex);
      value = match ? match[0] : '';
    } else if (this.pattern != null) {
      const match = value.match(this.pattern);
      value = match ? match[0] : '';
    }
    event.target.value = value;
  }

  increment(): void {
    if (typeof this.value === 'number' && this.checkValueInRange(this.value + 1)) {
      this.value++;
      this.onChange(this.value);
    }
  }

  decrement(): void {
    if (typeof this.value === 'number' && this.checkValueInRange(this.value - 1)) {
      this.value--;
      this.onChange(this.value);
    }
  }

  checkValueInRange(value: number): boolean {
    return (!(this.min !== undefined && value < this.min) && !(this.max !== undefined && value > this.max));
  }

  validate(c: FormControl) {
    let isValid = true;
    if (c.value) {
      const num = parseFloat(c.value);
      isValid = !isNaN(num) && this.checkValueInRange(num);
    } else {
      isValid = this.allowEmpty;
    }
    return isValid ? null : { rangeError: true };
  }
}
